gpt4 book ai didi

javascript - 使用when库理解javascript中的promise

转载 作者:行者123 更新时间:2023-11-28 20:03:58 25 4
gpt4 key购买 nike

我一直在尝试了解异步编程和 Promise 的使用。为了帮助理解它们,我编写了一些简单的嵌套代码,但遇到了障碍。

代码如下:http://pastebin.com/hBtk9vER确保在库时安装(npm install)

var when = require('when');

function promise() {
console.log("Promise");
promiseRead().then(function(string) {
console.log("Inner promise");
console.log(string);
});
}

function promiseRead() {
console.log("PromiseRead");
return baz().then(function() {
console.log("Inner Read");
var deferred = when.defer();
setTimeout(function() {
deferred.resolve("Hello World");
}, 5000);
});
}

function baz() {
console.log("BAZ");
return when(true);
}

promise();

我的问题是console.log(string)未定义,当我期望它是 "Hello World" 时之后promiseRead()解决了。有趣的是,当我删除超时时,它会按预期工作。任何人都可以帮忙解释一下为什么 promise函数正在 promiseRead() 之前执行它的代码已超时。

非常感谢

最佳答案

看起来您需要在 PromiseRead() 中返回延迟对象

关于javascript - 使用when库理解javascript中的promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21161344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com