不使用co模块
异步代码
getProjectProfile() {
console.log("2");
return new Promise(function (resolve, reject) {
console.log("3");
Editor.Profile.load('profile://project/project.json', (error, profile) => {
console.log("4");
if (error) {
return reject(error);
}
resolve(profile);
return profile;
});
});
},
2种方式
- then 实现同步
console.log("1");
this.getProjectProfile().then(profile => {
console.log(profile);
});
console.log("5");
- async 实现同步
(async ()=>{
console.log("1");
let p = await this.getProjectProfile();
console.log(p);
console.log("5");
})();
co模块实现同步(co+yield)
异步代码
child_process.execPromise = function (cmd, options, callback) {
return new Promise(function (resolve, reject) {
child_process.exec(cmd, options, function (err, stdout, stderr) {
// console.log("执行完毕!");
if (err) {
console.log(err);
callback && callback(stderr);
reject(err);
return;
}
resolve();
})
});
};
co(function(){
yield child_process.execPromise(cmd, null, function (err) {
this._addLog("出现错误: \n" + err);
}.bind(this));
});