回调以等待异步调用"/>
获取回调以等待异步调用
我对所有这些东西都很陌生,有几个关于 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小时内删除。
- 上一篇: 如何在 Strapi 自定义 API 中发送媒体
- 下一篇: Node,js Web Scrape
发布评论