0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Q.Promiseのnotifyは非同期的にかかないとprogressされない

Posted at

Promiseまわりで有名なライブラリQを使ってる中でハマったのでメモ。

問題

QのPromiseはdoneとfailに加えてprogressにも対応しているので使いやすい。
resolveするとdoneのコールバックが呼ばれるように、notifyしたらprogressのコールバックが呼ばれる。
が、同期的にnotifyを呼ぶとコールバックが実行されない。

(new Q.Promise((resolve, reject, notify)=>{
	notify('hoge');
	resolve('piyo');
})).progress((val)=>{
	//実行されない
	console.log('progress', val);
}).done((val)=>{
	//実行される
	console.log('done', val);
});

解決

ソースを見るとnextTickしてprogressのコールバックを実行している。

   deferred.notify = function (progress) {
       if (resolvedPromise) {
           return;
       }

       array_reduce(progressListeners, function (undefined, progressListener) {
           Q.nextTick(function () {
               progressListener(progress);
           });
       }, void 0);
   };

https://github.com/kriskowal/q/blob/v1/q.js

なので非同期的にかけば実行される。

(new Q.Promise((resolve, reject, notify)=>{
	setTimeout(()=>{
		notify('hoge');
	}, 0);
})).progress((val)=>{
	//実行される
	console.log('progress', val);
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?