获取回调以等待异步调用

编程入门 行业动态 更新时间:2024-10-07 16:17:01

获取<a href=https://www.elefans.com/category/jswz/34/1771356.html style=回调以等待异步调用"/>

获取回调以等待异步调用

我对所有这些东西都很陌生,有几个关于 Nodejs/js 中的异步和回调的问题。

我有以下小提琴设置:/

function updateTestVariable(key, callback) {
  console.log("2 ENTERupdateTestVariable key is: " + key);
  callback(key)
}

var testVariable = ""

console.log("1 BEFORE updateTestVariable is called testVariable is " + testVariable)

updateTestVariable("VARIABLE HAS UPDATED", async function(firstParam) {
  console.log("3 ENTER updateTestVariable firstParam is: " + firstParam);
  console.log("4 text before timeout starts testVariable is: " + testVariable)

  var mockingAsyncServiceCall = await setTimeout(() => {
    testVariable = firstParam
    console.log("5 AFTER TIMEOUT COMPLETE  testVariable is " + testVariable)
  }, 4000);

  console.log("6 line after timeout, testVariable is " + testVariable)
})

console.log("7 AFTER updateTestVariable is called testVariable is " + testVariable)
回答如下:

要让 5 在 4 之后出现,请考虑将

setTimeout()
包裹在
Promise
中。这允许回调正确地“等待”
setTimeout()
解决,然后调用 6。

对于最后一个 7,在

callback
中返回
updateTestVariable()
的调用结果,这样
updateTestVariable()
就会返回一个
Promise
,从而我们可以使用
.then()
仅在
updateTestVariable()
之后记录 7彻底解决

function updateTestVariable(key, callback) {
  console.log("2 ENTERupdateTestVariable key is: " + key);
  return callback(key)
}

var testVariable = ""

console.log("1 BEFORE updateTestVariable is called testVariable is " + testVariable)

updateTestVariable("VARIABLE HAS UPDATED", async function(firstParam) {
  console.log("3 ENTER updateTestVariable firstParam is: " + firstParam);
  console.log("4 text before timeout starts testVariable is: " + testVariable)

  var mockingAsyncServiceCall = await new Promise((resolve) => {
    setTimeout(() => {
      testVariable = firstParam
      console.log("5 AFTER TIMEOUT COMPLETE  testVariable is " + testVariable);
      resolve();
    }, 4000);
  });

  console.log("6 line after timeout, testVariable is " + testVariable);
}).then(() => console.log("7 AFTER updateTestVariable is called testVariable is " + testVariable));

更多推荐

获取回调以等待异步调用

本文发布于:2024-05-30 06:40:39,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!