我有两个功能。 function1()
比 function2()
需要更多时间才能完成,因为它执行获取请求。我需要按此顺序启动它们,但 function2()
的结果是第一个显示在 HTML DOM 上的。所以,我尝试用 promises 来解决这个问题。我将第一个函数设为变量,并创建了以下代码:
let promise1 = function1() {
fetch()
.then(do x)
.then(display x to HTML DOM)
return 0;
};
function2(a) {
// use the a;
// display some things to the HTML DOM based on `a`
}
promise1.then((a) => {
function2(a);
});
最初,这两个函数不需要相互交互,但为了使这与 Promise 一起工作,我通过使用 return
语句创建了一个人为的需求。但是,这不起作用:我收到 TypeError:promise1.then is not a function
错误。我浏览了一下“Learn more” ' 网页,但这些场景不适用于此处。
我对 JS 很陌生,对 Promise 也是个新手。我错过了什么吗?
最佳答案
您只需在第一个代码块中返回从 fetch
返回的 promise :
let promise1 = function1() {
return fetch()
.then(do x)
.then(() => {
//returns also need to be async
return 0;
});
//don't do this
// return 0;
// return inside the then() above
};
function2(a) {
// use the a;
// display some things to the HTML DOM based on `a`
}
promise1.then((a) => {
function2(a);
});
更详细地解释这一点;您的 fetch
异步运行。因此任何后续函数都不会等待(阻塞)。 fetch
返回一个 Promise
,允许您在异步函数完成时链接后续函数。因此,要在 fetch
之后运行任何内容,您需要使用 fetch
返回的 Promise
。 then
是 Promise
对象的一个函数,不是获取自身,要使用您需要返回的 Promise(在 Promise 对象上调用 then
)首先,因此返回 fetch()...
。 How do I return the response from an asynchronous call?详细介绍一下
关于JavaScript 没有兑现 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53495915/