Skip to content

Instantly share code, notes, and snippets.

@tkatochin tkatochin/file0.txt
Last active Jul 25, 2018

Embed
What would you like to do?
Promiseへの翻訳コードでasync/awaitの挙動を理解する ref: https://qiita.com/tkatochin/items/4603c4ec06fc6eb4f371
function hoge() {
// なんかかんか
var foo = ...
var bar = ...
if (foo < ...) {
return foo+bar;
}
var result = innerHoge(foo, bar);
var lastResult = ... // result使ってごにょごにょ
return lastResult;
}
function innerHoge(foo, bar) {
... // fooとbarをごにょごにょ
return ...;
}
function innerHoge(foo, bar, successCallback, errorCallback) {
// xhrでもなんでもいいけど成功と失敗かえす非同期の例として。fooとbarのごにょごにょは向こう側でやることに…
$.ajax({
url: "...",
data: { foo: foo, bar: bar },
success: function(data, status, xhr){
successCallback(data);
},
error: function(xhr, status, ex){
errorCallback(ex);
}
});
}
function innerHoge(foo, bar) {
return new Promise((resolve, reject)=>{
// xhrでもなんでもいいけど成功と失敗かえす非同期の例として。fooとbarのごにょごにょは向こう側でやることに…
$.ajax({
url: "...",
data: { foo, bar },
success: function(data, status, xhr){
resolve(data);
},
error: function(xhr, status, ex){
reject(ex);
}
});
});
}
async function hoge() {
// なんかかんか
var foo = ...
var bar = ...
if (foo < ...) {
return foo+bar;
}
var result = await innerHoge(foo, bar);
var lastResult = ... // result使ってごにょごにょ
return lastResult;
}
function hoge() {
// なんかかんか
var foo = ...
var bar = ...
if (foo < ...) {
return Promise.resolve(foo+bar);
}
return innerHoge(foo, bar).then(function(result){
var lastResult = ... // result使ってごにょごにょ
return lastResult;
});
}
function innerHoge(foo, bar) {
return fetch(`...?foo=${foo}&bar=${bar}`);
}
async function innerHoge(foo, bar) {
return await fetch(`...?foo=${foo}&bar=${bar}`);
}
(async function() {
var result;
try {
result = await hoge();
} catch(ex) {
// ex = hoge()が返したPromiseオブジェクトのcatchに渡された値
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.