Обещаю только не ждать

Я полностью переписываю свой вопрос, свяжите его еще дальше.

Почему в следующем коде x() приравнивать к undefined вместо success который записывается в консоль console.log('success');

Последняя строка завершается выполнением в консоли; тогда .then() обратный звонок срабатывает.

Как я могу сделать это так x() возвращает значение "success" до начала выполнения последней строки.

Даже yF() оценивается как undefined, Тем не менее, .then() повторяет th y: success,

const promise = require('promise');
const requestify = require('requestify');


function x() {
    requestify.get('https://<redacted>/')
        .then(function (d) {
            console.log('success', d.code);
            return 'success';
        })
        .fail(function (f) {
            console.log('fail', f.code);
            return 'fail';
        });
    ;
}


var yF = function () {
    yP   .then(function (th) { console.log("th", th); return th; })
        .catch(function (fl) { console.log("fl", fl); return fl; });
}


var yP = new Promise(
    function (resolve, reject) {
        if (1 == 1) {
            resolve("y: success");
        } else {
            reject(new Error("y: fail"));
        }
    }
);




console.log("hello", x());
console.log("world", yF());

2 ответа

Два подхода:

1) x() ~ Я позвоню, передам переменную вперед

2) yP()потребляя обещание

const promise = require('promise');
const requestify = require('requestify');

var f = "";


function yP() {
    return new Promise(function (resolve, reject) {
        requestify.get('https://<redacted>')
            .then(function (da) {
                var fpt = "success(yP):" + da.code.toString();
                console.log('success-yP', fpt);
                resolve(fpt);
            })
            .catch(function (ca) {
                var fpc = "fail(yP):" + ca.code.toString();
                console.log('fail-yP', fpc);
                reject(fpc);
            });
    });
}


function x() {
    requestify.get('https://<redacted>/')
        .then(function (da) {
            f = "success(x):" + da.code.toString();
            console.log('success-x', f);
            consumef();
        })
        .catch(function (ca) {
            f = "fail(x):" + ca.code.toString();
            console.log('fail-x', ca);
            consumef();
        });
    ;
}


function consumef() {
    console.log("hello", f);

}



x();
yP()
    .then(function (fyPt) { console.log('yP().then', fyPt); })
    .catch(function (fyPc) { console.log('yP().catch', fyPc); });

Отладчик прослушивает [::]:5858

успех-yp успех (yP):200

yP (). затем успех (yP):200

успех-х успех (х): 200

привет успех (х): 200

Функция x не возвращает значение. Этот пример может помочь:

> function foo() { console.log('hi from foo'); }
undefined
> console.log('calling foo', foo());
hi from foo
calling foo undefined

Вы должны вернуть обещание в вашей функции. функция x может измениться так:

function x() {
    return requestify.get('https://<redacted>/')
        .then(function (d) {
            console.log('success', d.code);
            return 'success';
        })
        .fail(function (f) {
            console.log('fail', f.code);
            return 'fail';
        });
}

Теперь вы можете позвонить x с then:

x().then(result => assert(result === 'success'));
Другие вопросы по тегам