gpt4 book ai didi

javascript - JS promise 未按预期解决

转载 作者:行者123 更新时间:2023-12-03 04:28:35 24 4
gpt4 key购买 nike

以下两个函数交换 promise 解析数据。第二个函数应该将对象返回给第一个函数的内部 Promise 的 then,但事实并非如此。

let functionA = function (stuff) {
var responseToGet;
return fetch(someURL
{
method: 'GET',
headers: {headers},
})
.then((resp) => {
responseToGet = resp;
return functionB(responseToGet)
})
.then((respFromB) => {
console.log('respFromB', respFromB); // WHY IS THIS UNDEFINED INSTEAD OF TRUE/FALSE ?
if (respFromB.status)
return null;
else
return respFromB.jsonObj;
})
.catch((error) => {
console.log(error);
});}



let functionB = function(response)
{
response.json().then((r2) => {
if (something)
return Promise.resolve({status: true, jsonObj: null});
else
return Promise.resolve({status: false, jsonObj: r2});
})
.done();}

最佳答案

您不需要调用“done”函数。只需从函数返回一个 promise 示例:

var functionA = function (stuff) {
var responseToGet;
return fetch("http://httpbin.org/gzip",
{
method: 'GET',
headers: {}
})
.then(function (resp) {
responseToGet = resp;
return functionB(responseToGet)
}).then(function (respFromB) {
console.log('respFromB', respFromB); // WHY IS THIS UNDEFINED INSTEAD OF TRUE/FALSE ?
if (respFromB.status)
return null;
else
return respFromB.jsonObj;
}).catch(function (error) {
console.log(error);
});
}

var functionB = function (response) {
var promise = response.json().then(function (r2) {
if (r2)
return Promise.resolve({status: true, jsonObj: null});
else
return Promise.resolve({status: false, jsonObj: r2});
});

return promise;
}

关于javascript - JS promise 未按预期解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594522/

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