无法解析调用其他方法的 Promise [英] Unable to resolve a Promise calling another method

查看:55
本文介绍了无法解析调用其他方法的 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解析已创建的 Promise.不知道问题出在哪里,请帮我解决这个问题.

I am unable to resolve a Promise that is created. Not sure where the problem is, please help me to resolve this.

const tsearch = async () => {
    console.log("calling")
    //requesting the relevant page data
    await new Promise((resolve) =>  {
        getData("wifi", 2, true); 
        return resolve("success")
    });
    console.log(finished);
}

function getData(url, callControl = 0, wifi = false) {
    if (!!url) {
        console.log(url + " - " + callControl)
    }
    if (callControl > 0)
    setTimeout(getData, 1000, url, --callControl)
    else {
        console.log("getData - else part - resolving")
        // Promise.resolve();
    }
}


tsearch();

推荐答案

asyncawait 旨在使您的程序更易于编写.令人震惊的是,有多少人使用它来使他们的程序更加复杂.您的问题中存在许多误解,这篇文章的其他答案中也存在许多其他误解 -

async and await is designed to make your programs easier to write. It's astounding how many people use it to make their programs more complicated. There are numerous misunderstandings presented in your question, and many others presented in other answers in this post -

async function tsearch () {
  console.log("calling")
  const result = await getData("wifi", 2, true)
  console.log("finished tsearch")
  return result
}

async function getData (url, callControl, wifi = false) {
  while (callControl > 0) {
    console.log(`${url} - ${callControl}`)
    callControl--
    await sleep(1000)
  }
  return "done"
}

function sleep (ms) {
  return new Promise(r => setTimeout(r, ms))
}

tsearch().then(console.log, console.error)

calling
wifi - 2
wifi - 1
finished tsearch
done

如果您想递归地编写 getData,这仍然是一个选项,就像任何 async 函数一样.第二个示例具有完全相同的行为并产生相同的输出 -

If you want to write getData recursively, that is still an option, as is the case with any async function. This second example has the exact same behaviour and produces the same output -

async function tsearch () {
  console.log("calling")
  const result = await getData("wifi", 2, true)
  console.log("finished tsearch")
  return result
}

async function getData (url, callControl, wifi = false) {
  if (callControl <= 0) return "done"
  console.log(`${url} - ${callControl}`)
  await sleep(1000)
  return getData(url, callControl - 1, wifi)
}

function sleep (ms) {
  return new Promise(r => setTimeout(r, ms))
}

tsearch().then(console.log, console.error)

有关误用 asyncawait 的更多信息,请参阅这些相关问答 -

For more info on misuse of async and await, please see these related Q&A's -

这篇关于无法解析调用其他方法的 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆