0
0

More than 1 year has passed since last update.

Javascriptでasync使うと、promiseが返ってきた...

Last updated at Posted at 2023-09-14

背景

JavaScriptで関数の戻り値が、普通の(?)戻り値ではなく、promiseが返ってきました。。
promiseとかきちんと理解しないまま使ってて、とりあえず同期とるならasync/await使えばいいや、くらいのノリで使っていたのが原因ですね。。。

・・・というわけで、初心者向けのメモ。。

環境

  • Windows 10 64bit
  • Node.js(v18.0.0)

Node.js のパッケージ

  • cmd > npm install express(今回express使わないですが。。)

sample1

javascript:sample1.js
const temp = test();
console.log(temp);

function test(){
    const a = "aaa"
    return a;
}
コマンドプロンプト
> aaa

aaaが出力されます。
まぁ、想定通りですよね。

sample2

javascript:sample2.js
const temp = test();
console.log(temp);

async function test(){
    const a = "aaa"
    return a;
}
コマンドプロンプト
> promise { 'aaa' }

!!!
なんと、promiseが返ってきました!
sample1とsample2の違いは、functionの前に、asyncを付けただけ。

async関数に対する戻り値は、promiseで返ってくるのですね。。(知らなかった。。。)

sample3

javascript:sample3.js
test2();

async function test2(){
    const ret = await test();
    console.log(ret)
}

async function test(){{
    const a = "aaa"
    return a;
}}
コマンドプロンプト
> aaa

test()は、前と同じですが、test()を呼ぶtest2()を作ってみました。
その関数の中で、awaitを使って、戻り値を取り出してみると・・・・

(promiseではない)欲しかった値が取得できた!!!

ちなみに、

sample4

javascript:sample3.js
test2();

async function test2(){
    const ret = test();
    console.log(ret)
}

async function test(){{
    const a = "aaa"
    return a;
}}
コマンドプロンプト
> promise { 'aaa' }

と、sample3のtest2()からawaitをとってしまうと、またpromiseが戻ってきました。。

awaitは、promiseの中身を取り出してくれるのですね。。
ありがたや、ありがたや、、(いまさら!?)

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