我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
我正在使用javascript为firebase写云函数,但是我被困住了,我不知道错误的确切含义并且无法解决。.错误状态:27:65错误每个then()应该返回一个值或抛出承诺/总是回报
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
if (!change.after.val()) {
return console.log('A Notification has been deleted from the database : ', notification_id);
}
const deviceToken = admin.database().ref(`/ServiceProvider/${user_id}/device_token`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title : "New Friend Request",
body: "You Have Received A new Friend …Run Code Online (Sandbox Code Playgroud) 我正在使用ESLint并且我收到此错误:每个then()都应该返回一个值或抛出promise/always-return
码:
return somePromise.then(result => {
console.log(result);
}).catch(error => {
console.error(error);
});
Run Code Online (Sandbox Code Playgroud)
我为什么要从这个承诺中回来?显然没有必要,因为我只想在日志中打印结果,就是这样.在所有情况下都适用这条规则似乎不对.我正在写一个Firebase数据库触发器,我相信它只对知道承诺是否已经解决感兴趣.
javascript ×4
promise ×3
bluebird ×2
q ×2
callback ×1
ecmascript-6 ×1
es6-promise ×1
eslint ×1
firebase ×1
node.js ×1