Я полностью переписываю свой вопрос, и он еще больше сварил его.
Почему в следующем коде 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());
Два подхода:
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
успех-x успех (x): 200
Привет успех (x): 200
yP
, просто верните значение.
Функция 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'));
hello { state: 'pending' }
. Спасибо за напоминание, что я могу вернуть requestify()
одиночку включил лампочку