我有這個承諾我簡化了代碼,但是我不能拒絕promise0
。在下面的例子中,renameProfile
首先讀取一個包含所有配置文件信息的文件,在讀取完畢後,它會嘗試重新命名它,這是沒有保證的。因此,例如readFile
成功,但重命名文件過程失敗。但它不拒絕。拒絕承諾,什麼時候不知道父母var
我使用Promise.jsm https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm
function doit() {
var promise1 = renameProfile(1);
promise1.then(
function() {
console.log('promise1 success');
},
function onReject(rsn) {
console.log('promise1 failed rsn = ' + rsn);
}
);
return promise1;
}
function renameProfile(readFileFirst) {
if (readFileFirst == 1) {
console.log('doing read file first');
var promise2 = readFile();
promise2.then(
function() {
console.log('promise2 success - read file success will now rename the profile');
return renameProfile(0);
},
function (rsn) {
console.log('promise2 failed - read file failed rsn = ' + rsn);
return new Error('read file failed rsn = ' + rsn);
}
);
return promise2;
} else if (readFileFirst == 0) {
//always reject promise
console.log('doing renameProfile');
return new Error('renameProfile failed');;
}
}
function readFile() {
let deferred = Promise.defer();
deferred.resolve('successfully read file');
return deferred.promise;
}
var promise0 = doit();
promise0.then(
function() {
console.log('promise0 success');
},
function (rsn) {
console.log('promise0 failed rsn = ' + rsn);
}
);
承諾爲您使用該庫的規範......? jQuery的承諾,還是什麼? –
嘿,我更新它有這個信息。我正在使用Firefox的Promise.jsm,我也更新了例子,所以它的工作原理,如果你從Firefox中的scratchpad運行它 – Noitidart