承诺的回报价值

时间:2018-06-01 12:32:16

标签: typescript promise

我错过了一些承诺的概念(在TS中)。我不明白为什么以下代码不会在控制台上打印data 222参数。

const p : Promise<number> = 
    new Promise<number>(()=>{console.log(1); return 222;})
    .then((data)=>{
    console.log(data)
    return 43;
});

它仅打印1而不是1,然后是222。感谢。

3 个答案:

答案 0 :(得分:2)

承诺不返回值,它使用值结算:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="213dp"
            android:orientation="vertical"
            android:paddingLeft="24dp"
            android:paddingRight="24dp"
            android:paddingTop="56dp"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="16dp"
            tools:ignore="MissingConstraints">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="8dp"
                    android:layout_marginTop="8dp"
                    android:textColor="@color/colorPrimaryDark"
                    android:textSize="16sp"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="8dp"
                    android:layout_marginTop="8dp" />

                <TextView

                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="2dip"
                    android:textColor="@color/colorAccent" />

        </LinearLayout>
</android.support.constraint.ConstraintLayout>

答案 1 :(得分:1)

你需要解决这个承诺:

const p : Promise<number> = 
new Promise<number>((resolve)=>{
    console.log(1); 
    resolve(222);}
)
.then(
    (data) =>{
    console.log(data);
    return 43;
 });

答案 2 :(得分:1)

承诺是异步操作,

const p : Promise<number> = 
    new Promise<number>((resolve, reject)=>{
      //do some operations here, and the desired output is ready, say result = 5;
      resolve(result)
      //or if you hit an error you can get the error obj, e and
      reject(e)
    });

您现在可以执行承诺调用,执行后的结果将在.then

中提供
p()
.then((resolvedResult:number)=>console.log(resolvedResult),(rejectedError)=>console.log(rejectedError))
相关问题