JS承诺不会按预期解决

时间:2017-04-24 17:38:04

标签: javascript react-native promise

以下两个函数交换承诺解析数据。第二个函数应该将对象返回到第一个函数的内部承诺,但它没有。

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();}

1 个答案:

答案 0 :(得分:1)

你不需要打电话完成'功能。 只需从functionB返回一个承诺

示例:

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;
}